<?php

header("Content-type: text/html; charset=utf-8");

$page = $_GET['page']; // get the requested page 
$limit = $_GET['rows']; // get how many rows we want to have into the grid 
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort 
$sord = $_GET['sord']; // get the direction 

$admin = true;
require_once('auth_req.inc.php');

$where_clause = "";

if (isset($_GET['type']) && ($_GET['type'] >= 0) && ($_GET['type'] <= 2))
{
    $where_clause .= "log_type=" . $_GET['type'];   
}

if (isset($_GET['imp']) && ($_GET['imp'] >= 0) && ($_GET['imp'] <= 2))
{
    if (!empty($where_clause))
    {
        $where_clause .= " and ";
    }

    $where_clause .= "imp=" . $_GET['imp'];
}

if (isset($_GET['cid']) && ($_GET['cid'] >= 0))
{
    if (!empty($where_clause))
    {
        $where_clause .= " and ";
    }

    $where_clause .= "c_id=" . $_GET['cid'];
}

if (!empty($where_clause))
{
    $where_clause = ' where ' . $where_clause;
}

$rs = $dbh->query('select count(*) from log'.$where_clause);

if ($rec = $rs->fetchAll(PDO::FETCH_COLUMN, 0))
{
    $count = $rec[0];
}
else
{
    $count = 0;
}

if( $count > 0 ) 
{ 
    $total_pages = ceil($count/$limit); 
} 
else 
{ 
    $total_pages = 0; 
} 

if ($page > $total_pages) 
    $page=$total_pages;


$start = $limit * $page - $limit;

if ($start < 0) 
    $start = 0;


$sth = $dbh->prepare('select * from log '.$where_clause.' order by ' . $sidx . ' ' . $sord  . ' limit :start,:limit');

$sth->bindParam(':start', intval($start), PDO::PARAM_INT);
$sth->bindParam(':limit', intval($limit), PDO::PARAM_INT);

$sth->execute();

$responce->page = intval($page); 
$responce->total = $total_pages; 
$responce->records = intval($count); 

$alldb = $sth->fetchAll(PDO::FETCH_ASSOC);

$count=0;

foreach( $alldb as $key => $val)
{
    $responce->rows[$key]['id'] = $val['log_id'];

    $val['log_msg'] = preg_replace('/\[(.*)\]/suU', '<b>$1</b>',$val['log_msg']);

    if (is_null($val[log_user]))
    {
        $val[log_user] = '';
    }

    if (is_null($val[c_id]))
    {
        $val[c_id] = '&nbsp;';
    }

    $st = "";
    $end = "";

    switch ($val['imp'])
    {
        case 1:
            $st= '<span style="color:green">';
            $end = '</span>';
        break;    

        case 2:
            $st= '<span style="color:red">';
            $end = '</span>';
        break;    

    }
    
    if (!$feature_alarm)
    {
    	$responce->rows[$key]['cell'] = array($val['log_date'],$val['c_id'],$val['user'], $st.$val['log_msg'].$end);
    }
    else 
    {
    	if (isset($val['log_confirm_date']))
    	{
			$date = $val['log_confirm_date'];
    	}
    	elseif ($val['imp'] > 1)
		{
			$date = '-';
		}
		   	
    	$responce->rows[$key]['cell'] = array($val['log_date'],$val['c_id'],$val['user'], $st.$val['log_msg'].$end, $date, $val['log_confirm_user']);
    }
}

echo json_encode($responce);

?>
